package com.bluemsun.filter;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Steve Paul
 * 用于过滤掉空格
 */
public class NoSpaceFilter implements Filter
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /**
     * 过滤掉空格和空输入等违法输入输出
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String username = servletRequest.getParameter("username");
        String password = servletRequest.getParameter("password");
        servletResponse.setContentType("text/html;charset=utf-8");
        PrintWriter pw = servletResponse.getWriter();
        if (username.indexOf(' ') != -1 || password.indexOf(' ') != -1) {
            pw.println("无效的账号和密码!不允许有空格!");

        } else if("".equals(username) || "".equals(password)){
            pw.println("无效的账号和密码!不允许为空!");
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
        pw.close();
    }

    @Override
    public void destroy() {
    }
}
